from datetime import datetime
from extensions import db
import sqlalchemy as sa


class ArticleORM(db.Model):
    """新闻"""
    __tablename__ = "forum_article"

    id = sa.Column(sa.Integer, primary_key=True)  # 新闻编号
    title = sa.Column(sa.String(256), nullable=False)  # 新闻标题
    source = sa.Column(sa.String(64), nullable=False)  # 新闻来源
    digest = sa.Column(sa.String(512), nullable=False)  # 新闻摘要
    content = sa.Column(sa.Text, nullable=False)  # 新闻内容
    clicks = sa.Column(sa.Integer, default=0)  # 浏览量
    index_image_url = sa.Column(sa.String(256))  # 新闻列表图片路径
    status = sa.Column(sa.Integer, default=0)  # 当前新闻状态 如果为0代表审核通过，1代表审核中，-1代表审核不通过
    reason = sa.Column(sa.String(256))  # 未通过原因，status = -1 的时候使用

    category_id = sa.Column(sa.Integer, sa.ForeignKey("forum_category.id"))
    # 通过category_id反向获取分类名称
    category_articles = db.relationship("CategoryORM", backref=db.backref('forum_article' ,lazy=True))
    user_id = sa.Column(sa.Integer, sa.ForeignKey("forum_user.id"))  # 当前新闻的作者id

    create_at = sa.Column(sa.DateTime, default=datetime.now)  # 记录的创建时间
    update_at = sa.Column(sa.DateTime, default=datetime.now, onupdate=datetime.now)  # 记录的更新时间

    # 收藏文章的用户
    use_list = db.relationship(
        'UserORM',
        secondary='forum_user_collection',
        lazy='dynamic'
    )

    comment_list = db.relationship("CommentORM", lazy="dynamic", overlaps="collection_article_list")

    def save(self):
        db.session.add(self)
        db.session.commit()

    def delete(self):
        db.session.delete(self)
        db.session.commit()

    def get_category_name(self):
        if self.category_articles.name:
            return self.category_articles.name
        else:
            return 'unknown'

    def to_dict(self):
        return {
            'id': self.id,
            'title': self.title,
            'source': self.source,
            'digest': self.digest,
            'content': self.content,
            'clicks': self.clicks,
            'index_image_url': self.index_image_url,
            'status': self.status,
            'reason': self.reason,
            'category_id': self.category_id,
            'category_name':self.get_category_name(),
            'user_id': self.user_id,
            'create_at': self.create_at.strftime('%Y-%m-%d %H:%M:%S'),
        }
